<?php
declare(strict_types=1);
/**
 * @project: 兔兔找图微信小程序
 * @author: kert
 * @date: 2023/5/16
 * @link: https://www.tutudati.com/
 * @site: 微信搜索-兔兔找图
 */

namespace App\Logic\User\Repository\Image;

use App\Library\SnowFlakeId;
use App\Logic\User\Repository\UserRepositoryInterface;
use App\Models\User\Image\ImageDownload;
use App\Models\User\Image\ImageItemModel;
use App\Models\User\Image\ImageModel;
use Closure;
use Throwable;

class ImageItemRepository implements UserRepositoryInterface
{

    public function repositorySelect(Closure $closure, int $perSize, array $searchFields = []): array
    {
        $items = ImageItemModel::query()
            ->with(["author:uid,qr_url,nickname,remark"])
            ->where($closure)
            ->orderByDesc("orders")
            ->paginate($perSize, $searchFields);

        return [
            "items" => $items->items(),
            "total" => $items->total(),
            "page" => $items->currentPage(),
            "size" => $items->perPage(),
        ];
    }

    public function repositoryCreate(array $insertInfo): bool
    {
        return false;
    }

    public function repositoryFind(Closure $closure, array $searchFields = []): array
    {
        $bean = ImageItemModel::query()->where($closure)->first($searchFields);

        return !empty($bean) ? $bean->toArray() : [];
    }

    public function repositoryUpdate(array $updateWhere, array $updateInfo): int
    {
        return 0;
    }

    public function repositoryWhereInDelete(array $deleteWhere, string $field): int
    {
        return 0;
    }

    public function repositoryDelete(array $deleteWhere): int
    {
        return 0;
    }

    public function incrByDownload(string $imageUid, string $imageItemUid, string $authorUid, string $userUid): int
    {
        try {
            ImageDownload::query()->create([
                "uid" => SnowFlakeId::getId(),
                "author_uid" => $authorUid,
                "user_uid" => $userUid,
                "image_uid" => $imageUid,
                "image_item_uid" => $imageItemUid,
            ]);
            ImageModel::query()->where("uid", "=", $imageUid)->increment("download", 1);
            ImageItemModel::query()->where("uid", "=", $imageItemUid)->increment("download", 1);
            return 1;
        } catch (Throwable $throwable) {
            return 0;
        }
    }
}
